package com.binance.assetservice.web.service.impl;


import com.alibaba.fastjson.JSON;
import com.binance.account.api.UserApi;
import com.binance.account.vo.security.request.UserIdRequest;
import com.binance.account.vo.user.response.GetUserResponse;
import com.binance.assetservice.web.service.IBaseService;
import com.binance.master.enums.LanguageEnum;
import com.binance.master.enums.TerminalEnum;
import com.binance.master.error.BusinessException;
import com.binance.master.error.GeneralCode;
import com.binance.master.models.APIRequest;
import com.binance.master.models.APIResponse;
import com.binance.master.utils.TrackingUtils;

import javax.annotation.Resource;

public abstract class BaseServiceImpl implements IBaseService {

    @Resource
    private UserApi userApi;

    @Override
    public GetUserResponse getUser(String userId) throws Exception {
        UserIdRequest body = new UserIdRequest();
        body.setUserId(Long.parseLong(userId));
        return this.getAPIRequestResponse(this.userApi.getUserById(this.newAPIRequest(body)));
    }

    @Override
    public GetUserResponse getCheckedUser(String userId) throws Exception {
        GetUserResponse response = this.getUser(userId);
        if (null == response || response.getUserInfo().getTradingAccount() == null) {
            throw new BusinessException(GeneralCode.USER_ACCOUNT_NOT_EXIST);
        }
        return response;
    }

    @Override
    public <T> APIRequest<T> newAPIRequest(T body) {
        APIRequest<T> request = new APIRequest<>();
        request.setBody(body);
        request.setLanguage(LanguageEnum.EN_US);
        request.setTerminal(TerminalEnum.WEB);
        request.setTrackingChain(TrackingUtils.getTrackingChain());
        return request;
    }

    @Override
    public <T> T getAPIRequestResponse(APIResponse<T> response) {
        if (APIResponse.Status.OK.equals(response.getStatus())) {
            return response.getData();
        } else {
            Object errorData = response.getErrorData();
            if (errorData == null) {
                errorData = response.getSubData();
            }
            throw new BusinessException(GeneralCode.findByCode(response.getCode()), JSON.toJSONString(errorData));
        }
    }



}
